import json
from venv import logger
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from ..models import Bot, Conversation, BotPublishHistory
from ..serializers import BotSerializer, ConversationSerializer
import requests  # type: ignore
from django.conf import settings  # 引入 settings

from ..services.prompt_service import PromptGenerationService
from .BaseResponse import BaseResponse

class BotCreateView(APIView):
    """
    智能体创建和列表API

    post:
    创建新的智能体

    参数:
    - space_id: 空间ID (必填)
    - name: 智能体名称 (必填)
    - description: 智能体描述 (必填)
    - prompt_info: 智能体角色设定 (可选，如不提供将自动生成)
    - category: 智能体类别 (可选，用于选择预设模板，如不提供将自动检测)

    如果未提供prompt_info，系统将:
    1. 尝试根据name和description自动检测智能体类别
    2. 使用AI服务生成结构化的prompt_info
    3. 如果AI生成失败，则使用预设模板

    get:
    获取当前用户创建的所有智能体
    """
    permission_classes = [permissions.IsAuthenticated]  # 确保用户已登录

    def post(self, request):
        # 获取 Coze 平台的令牌（从环境变量中获取）
        coze_access_token = settings.COZE_ACCESS_TOKEN
        if not coze_access_token:
            return BaseResponse.error("Missing Coze access token", status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 获取请求数据
        space_id = request.data.get("space_id")
        name = request.data.get("name")
        description = request.data.get("description")
        prompt_info = request.data.get("prompt_info")
        category = request.data.get("category", "")  # 可选参数，用于选择预设模板

        # 检查必填字段
        if not all([space_id, name, description]):
            logger.error("Missing required fields in request data")
            return Response({"error": "Missing required fields: space_id, name, description"},
                            status=status.HTTP_400_BAD_REQUEST)

        # 如果用户没有提供prompt_info，则自动生成
        if not prompt_info:
            # 如果用户没有指定类别，则自动检测
            if not category:
                category = PromptGenerationService.detect_category(name, description)

            # 尝试使用AI服务生成prompt_info
            generated_prompt = PromptGenerationService.generate_prompt(name, description)

            # 如果AI生成失败，则使用预设模板
            if not generated_prompt:
                generated_prompt = PromptGenerationService.get_default_prompt(category)

            prompt_info = generated_prompt

            # 记录生成的prompt_info
            logger.info(f"Generated prompt_info for bot '{name}' (category: {category}): {prompt_info[:100]}...")

        # 调用 Coze API 创建智能体
        url = "https://api.coze.cn/v1/bot/create"
        headers = {
            "Authorization": f"Bearer {coze_access_token}",
            "Content-Type": "application/json"
        }
        data = {
            "space_id": space_id,
            "name": name,
            "description": description,
            "prompt_info": {"prompt": prompt_info}
        }

        response = requests.post(url, json=data, headers=headers)

        if response.status_code == 200:
            # 解析返回数据
            api_response = response.json()
            if api_response.get("code") == 0:
                print("API Response:", api_response)  # 添加这行调试代码
                bot_id = api_response.get("data", {}).get("bot_id")  # 从 data 字段中提取 bot_id
                print("Bot ID from API:", bot_id)  # 添加这行调试代码
                # 创建成功，保存到数据库
                bot_data = {
                    "user": request.user.id,  # 关联当前用户
                    "space_id": space_id,
                    "name": name,
                    "description": description,
                    "prompt_info": prompt_info,
                    # "onboarding_info": onboarding_info,
                    "bot_id": bot_id,

                }
                serializer = BotSerializer(data=bot_data)
                if serializer.is_valid():
                    serializer.save()  # 保存到数据库
                    return BaseResponse.success(serializer.data)  # 返回创建成功的数据
                return BaseResponse.error(serializer.errors)
            else:
                # API 调用失败
                return BaseResponse.error(api_response.get("msg"))
        else:
            # 请求失败
            return BaseResponse.error("Failed to create bot", status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def get(self, request):
        # 获取当前用户创建的所有智能体
        bots = Bot.objects.filter(user=request.user)
        serializer = BotSerializer(bots, many=True)
        return BaseResponse.success(serializer.data)